import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { FormModal } from '../form-modal'
import { Check, ChevronDown, SearchIcon } from "lucide-react";
import classNames from 'classnames'
import { Input } from '@/components/ui/input';
import { Checkbox } from "@/components/ui/checkbox"
// 封装一个select组件
// 在m端使用drawer弹窗选择内容
// 在pc端通过popover选择内容
interface Option {
  value: string
  label: string
  [key: string]: any
}
interface SelectProps {
  value: string | string[]
  onChange: (value: string | string[]) => void
  name: string
  options: Option[]
  // 返回的内容是option对象
  triggerRender?: (option: Option | Option[]) => React.ReactNode
  // isClearable 是否可清除 默认false
  isClearable?: boolean
  // 是否可多选, 多选时,isClearable无效 默认false
  multiple?: boolean
}
const Select = ({ value, onChange, name, options, triggerRender, isClearable = false, multiple = false }: SelectProps) => {
  // 选框开启状态
  const [open, setOpen] = useState(false)

  // 处理延后选中数据
  const [selectedValue, setSelectedValue] = useState<Option[]>([])

  // 搜索内容
  const [search, setSearch] = useState('')
  // 是否显示搜索框
  const isShowSearch = options.length > 20
  // 过滤后的选项
  const filteredOptions = options.filter((option) => option.label.toLowerCase().includes(search.toLowerCase()))

  // 默认触发器
  const defaultTrigger = <Button variant="outline" className='w-[200px] justify-between'>
    <span className='line-clamp-1'>
      {
        value && value.length > 0 ? (multiple ? 
        (Array.isArray(value) ? <div>{value.map((v) => options.find((option) => option.value === v)?.label).join(', ')}</div> : '') : 
        options.find((option) => option.value === value)?.label || `Select ${name}`) : `Select ${name}`
      }
    </span>
    <ChevronDown className={classNames('transition-transform', {
      'rotate-180': open
    })} />
  </Button>

  // 打开关闭
  const handleOpenChange = (open: boolean) => {
    setOpen(open)
  }

  // 选中
  const handleSelect = (option: Option) => {
    if (multiple) { // 多选
      if(Array.isArray(selectedValue) && selectedValue.some((v: Option) => v.value === option.value)){ //如果已经存在在数组中
        // onChange(value.filter((v: string) => v !== option.value))
        setSelectedValue(selectedValue.filter((v: Option) => v.value !== option.value))
        return
      } else {
        // onChange([...(Array.isArray(value) ? value : []), option.value])
        setSelectedValue([...selectedValue, option])
      }
    } else { // 单选
      if (value === option.value && isClearable) {
        // 如果当前选项是选中的，则清除选项
        onChange('')
      } else {
        onChange(option.value)
      }
      setOpen(false)
    }
  }


  return (<FormModal
    open={open}
    showMaxSize={isShowSearch}
    onOpenChange={handleOpenChange}
    trigger={
      triggerRender ? triggerRender( //判断是否传入自定义触发器
        multiple ? options.filter( //多选时
          (option) => Array.isArray(value) && value.includes(option.value)
        ) : options.find((option) => option.value === value) || {value: '', label: ''}
      ) : defaultTrigger
    }
    header={name}
    slot={
      isShowSearch && <div className='flex items-center gap-2 border-b border-gray-200 pb-2'>
        <SearchIcon /> <Input placeholder="Search" className="w-full border-none outline-none shadow-none focus:!ring-0" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>
    }
    content={
      <>
        {filteredOptions.length > 0 ? <ul className={classNames('flex flex-col overflow-y-auto')}>
          {filteredOptions.map((option) => (
            <li key={option.value}>
              <Button variant="ghost" className='w-full justify-between max-md:px-0 text-[#333]' onClick={()=>handleSelect(option)}>
                <span className='flex items-center gap-2'>{multiple && <Checkbox checked={multiple ? Array.isArray(selectedValue) && selectedValue.some((v: Option) => v.value === option.value) : selectedValue.some((v: Option) => v.value === option.value)} />} {option.label}</span>
                {!multiple && value === option.value && <Check />}
              </Button>
            </li>
          ))}
        </ul> : <div className='flex items-center justify-center h-full'>No results</div>}
      </>
    }
    footer={
      multiple ?
      // 清除选项
      <div className='flex items-center gap-2'>
        <Button variant="outline" className='flex-1' onClick={() => {
          // onChange([])
          setSelectedValue([])
        }}>Clear All</Button>
        <Button className='flex-1' onClick={() => {
          onChange(selectedValue.map((v: Option) => v.value) as string[])
          setOpen(false)
        }}>Confirm</Button>
      </div>
      : null
    }
/>)
}

export default Select